import React, { Component } from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import {
  Table, Form, Popup, Input,
} from 'semantic-ui-react'
import Styled from 'styled-components'
import { BasicButton, PrimaryButton } from 'components/Button'
import { ValidInput, ValidType } from 'components/validForm'
import { SketchPicker } from 'react-color'

const SectionRow = Styled.div`
  margin-bottom: 1em;
`
class DatasetConfig extends Component {
  static propTypes = {}

  randomHexColor = () => {
    // 随机生成十六进制颜色
    let hex = Math.floor(Math.random() * 16777216).toString(16) // 生成ffffff以内16进制数
    while (hex.length < 6) {
      // while循环判断hex位数，少于6位前面加0凑够6位
      hex = `0${hex}`
    }
    return `#${hex}` // 返回‘#'开头16进制颜色
  }

  componentDidMount = () => {
    const { actionInitField, name, required } = this.props

    actionInitField({
      name,
      state: 'success',
      required,
      value: this.randomHexColor(),
    })
  }

  render() {
    const {
      header,
      description,
      actionInitField,
      actionFieldChange,
      field,
      submit,
      name,
      ...others
    } = this.props
    return (
      <Table.Row>
        <Table.Cell width="4" verticalAlign="top">
          {header}
        </Table.Cell>
        <Table.Cell>
          <SectionRow>{description}</SectionRow>
          <SectionRow>
            <Form>
              {field && (
                <Popup
                  trigger={(
                    <Form.Field width={5}>
                      <Input
                        label={{ style: { backgroundColor: field.value, width: '4em' } }}
                        labelPosition="right"
                        type="text"
                        onChange={(e, d) => actionFieldChange(d.name, d.value, d.rules)}
                        value={field.value.toUpperCase()}
                        fluid
                      />
                    </Form.Field>
)}
                  on="focus"
                  hideOnScroll
                >
                  <Popup.Content>
                    <SketchPicker
                      color={field.value}
                      onChangeComplete={({ hex }) => actionFieldChange(name, hex)}
                    />
                  </Popup.Content>
                </Popup>
              )}
            </Form>
          </SectionRow>
          {submit && (
            <SectionRow>
              <BasicButton content="取消" />
              <PrimaryButton content="保存" primary />
            </SectionRow>
          )}
        </Table.Cell>
      </Table.Row>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  field: validFormDuck.selectors.field(state, ownProps.name),
})

const mapDispatchToProps = {
  actionInitField: validFormDuck.creators.actionInitField,
  actionFieldChange: validFormDuck.creators.actionFieldChange,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(DatasetConfig)
